<?php
/**
 * Created by PhpStorm.
 * User: HP
 * Date: 2018/5/8
 * Time: 16:40
 */

namespace app\index\controller;

use app\common\Common;
use app\data\ShopData;
use app\data\UserData;
use app\order\Order;
use app\shop\Shop;
use think\Db;
use think\Exception;
use wechat\wxBizDataCrypt;

class User extends Base
{

    /**
     * 用户名字长度限制
     * @var array
     */
    private $userName = [1, 50];

    /**
     * 收货详细地址长度限制
     * @var array
     */
    private $deliveryAddress = [1, 150];

    private $lv = [1, 2, 3, 4, 5];

    /**
     * 排序方法
     * @var array
     */
    private $sortType = ['desc', 'asc'];

    /**1
     * 商户排序字段
     * @var array
     */
    private $bargainSort = ['create_time'];

    /**
     * 添加用户
     * @param $user_name
     * @param $user_head_img
     * @param $user_sex
     * @param $user_open_id
     * @param $union_id
     * @param $province
     * @param $city
     * @param $session_key
     * @return \think\response\Json
     */
    public function addUser($user_name, $user_head_img, $user_sex, $user_open_id, $union_id, $province, $city, $session_key)
    {
        $file = "./temp.txt";
        $fp = fopen($file, 'r');
        $res = session($union_id);
        if (empty($res)) {
            $id = Common::getTableValue(
                'drh_user_info',
                'id',
                ['union_id'],
                [$union_id]
            );
            if (empty($id)) {//首次登陆
                $user = new UserData();
                fclose($fp);
                return json($user->addUser($user_name, $user_head_img, $user_sex, $user_open_id, $union_id, $province, $city,$session_key));
            } else {//非首次登陆
                session($union_id, $id);
                fclose($fp);
                return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => ['user_id' => $id, 'open_id' => $user_open_id,'session_key'=>$session_key]]);
            }
        } else {
            fclose($fp);
            return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => ['user_id' => $res, 'open_id' => $user_open_id,'session_key'=>$session_key]]);
        }
    }

    /**
     * 修改用户信息
     * @param $user_open_id
     * @param $user_name
     * @param $user_head_img
     * @param $user_sex
     * @param $user_tel
     * @return array|\think\response\Json
     */
    public function editUser($user_open_id, $user_name, $user_head_img, $user_sex, $user_tel)
    {

        if (Common::checkTableFields('drh_user_info', 'user_open_id', $user_open_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }

        $check = ['用户名称' => ["{$this->userName[0]},{$this->userName[1]}", $user_name]];
        $res = Common::checkLength($check);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }

        if ($user_sex != 0 && $user_sex != 1) {
            return json(['code' => $this->f_code, 'msg' => '性别填写错误']);
        }
        //电话号码校验
        if (!Common::checkTel($user_tel)) {
            return json(['code' => $this->f_code, 'msg' => '电话号码格式错误']);
        }
        $tel = Common::getTableValue('drh_user_info', 'id', ['user_tel'], [$user_tel]);
        if (!empty($tel)) {
            return json(['code' => $this->f_code, 'msg' => '电话号码以存在']);
        }

        $user = new UserData();

        return json($user->editUser($user_open_id, $user_name, $user_head_img, $user_sex, $user_tel));
    }

    public function checkAddress($user_id, $user_name, $user_tel, array $address_province, array $address_municipal,
                                 array $address_district, $delivery_address, $zip_code)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $check = [
            '收货人姓名' => ["{$this->userName[0]},{$this->userName[1]}}", $user_name],
            '收货地址' => ["{$this->deliveryAddress[0]},{$this->deliveryAddress[1]}", $delivery_address],
        ];
        $res = Common::checkLength($check);
        if ($res['code'] == $this->f_code) {
            return $res;
        }
        //电话号码校验
        if (!Common::checkTel($user_tel)) {
            return ['code' => $this->f_code, 'msg' => '电话号码格式错误'];
        }
        if (strlen($zip_code) != 6 || !is_numeric($zip_code)) {
            return ['code' => $this->f_code, 'msg' => '邮编错误'];
        }
        $area = Common::getArea($address_district);
        if ($area['municipal_id'] != $address_municipal['id'] || $area['province_id'] != $address_province['id']) {
            return ['code' => $this->f_code, 'msg' => '地址填写错误'];
        }
        return ['code' => $this->t_code];
    }

    /**
     * 添加地址
     * @param $user_id
     * @param $user_name
     * @param $user_tel
     * @param $address_province
     * @param $address_municipal
     * @param $address_district
     * @param $delivery_address
     * @param string $zip_code
     * @return array|\think\response\Json
     */
    public function addAddress($user_id, $user_name, $user_tel, array $address_province, array $address_municipal,
                               array $address_district, $delivery_address, $zip_code = '000000')
    {
        $res = $this->checkAddress($user_id, $user_name, $user_tel, $address_province, $address_municipal,
            $address_district, $delivery_address, $zip_code);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $area = Common::getArea($address_district);
        if ($area['municipal_id'] != $address_municipal['id'] || $area['province_id'] != $address_province['id']) {
            return json(['code' => $this->f_code, 'msg' => '地址填写错误']);
        }
        $user = new UserData();
        $count = $user->getAddressCount($user_id);
        if ($count['count'] >= 20) {
            return json(['code' => $this->t_code, 'msg' => '收货地址最多20个']);
        }
        return json($user->addAddress($user_id, $user_name, $user_tel, $delivery_address,
            $zip_code, $area['province'], $area['municipal'], $area['district'],
            $address_province['id'], $address_municipal['id'], $address_district['id']));
    }

    /**
     * 修改地址
     * @param $id
     * @param $user_id
     * @param $user_name
     * @param $user_tel
     * @param array $address_province
     * @param array $address_municipal
     * @param array $address_district
     * @param $delivery_address
     * @param string $zip_code
     * @return \think\response\Json
     */
    public function editAddress($id, $user_id, $user_name, $user_tel, array $address_province, array $address_municipal,
                                array $address_district, $delivery_address, $zip_code = '000000')
    {
        $res = $this->checkAddress($user_id, $user_name, $user_tel, $address_province, $address_municipal,
            $address_district, $delivery_address, $zip_code);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $area = Common::getArea($address_district);
        if ($area['municipal_id'] != $address_municipal['id'] || $area['province_id'] != $address_province['id']) {
            return json(['code' => $this->f_code, 'msg' => '地址填写错误']);
        }
        $user = new UserData();
        return json($user->editAddress($id, $user_id, $user_name, $user_tel, $delivery_address,
            $zip_code, $area['province'], $area['municipal'], $area['district']
            , $address_province['id'], $address_municipal['id'], $address_district['id']));
    }

    /**
     * 显示收货地址
     * @param $user_id
     * @return \think\response\Json
     */
    public function showAddress($user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $user = new UserData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $user->showAddress($user_id),
                'default_id' => $user->getDefaultAddress($user_id)
            ]
        ]);
    }

    /**
     * 显示收货地址详细信息
     * @param $user_id
     * @param $id
     * @return mixed
     */
    public function showAddressInfo($user_id, $id)
    {
        $user = new UserData();
        $data = $user->showAddress($user_id, $id);
        return json_encode([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => empty($data) ? [] : $data
        ]);
    }

    /**
     * 删除收货地址
     * @param $id
     * @param $user_id
     * @return \think\response\Json
     */
    public function delAddress($id, $user_id)
    {
        $user = new UserData();
        return json($user->delAddress($id, $user_id));
    }

    /**
     * 用户订单显示
     * @param $open_id
     * @param int $page
     * @param int $pre
     * @param $status
     * @param array $sort
     * @return \think\response\Json
     */
    public function showOrder($open_id, $status = 0, $page = 1, $pre = 15,
                              array $sort = ['order_start_time' => 'desc'])
    {
        $order = new Order();
        return $order->showUserOrder($open_id, $status, $page, $pre, $sort);
    }

    /**
     * 用户订单详情显示
     * @param $id
     * @param $open_id
     * @param $order_num
     * @return \think\response\Json
     */
    public function showOrderInfo($id, $open_id, $order_num)
    {
        $order = new Order();
        return $order->showUserOrderInfo($id, $open_id, $order_num);
    }
//   站不开放
//    /**
//     * 积分转换为金钱
//     * @param $user_open_id
//     * @param $integral
//     * @return \think\response\Json
//     */
//    public function integralToMoney($user_open_id, $integral)
//    {
//        if (Common::checkTableFields('drh_user_info', 'user_open_id', $user_open_id) == $this->f_code) {
//            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
//        }
//        $user = new UserData();
//        $userInfo = $user->getInfo($user_open_id, ['user_integral', 'user_money', 'id']);
//        $user_integral = $userInfo['user_integral'];
//
//        if ($integral < 0 || $user_integral < $integral || !Common::checkFloat($integral)) {
//            return json(['code' => $this->f_code, 'msg' => '积分输入错误']);
//        }
//        return json($user->integralToMoney($integral, $userInfo));
//    }


    /**
     * 分销
     * @param $user_id
     * @param $user_open_id
     * @return \think\response\Json
     */
    public function addDistributionUser($user_id, $user_open_id)
    {
        $open_id = Common::getTableValue('drh_user_info', 'user_open_id', ['id'], [$user_id]);
        if (empty($open_id) || $open_id == $user_open_id) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        if (Common::checkTableFields('drh_user_info', 'user_open_id', $user_open_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $user = new UserData();
        $userInfo = $user->getInfo($user_open_id, ['id']);
        $id = $userInfo['id'];
        return json($user->addDistributionUser($user_id, $id));
    }

    /**
     * 用户创建砍价商品
     * url还未生产
     * @param $goods_id
     * @param $shop_id
     * @param $user_id
     * @return \think\response\Json
     */
    public function createBargainOrder($goods_id, $shop_id, $user_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $shop = new ShopData();
        $bargain_info = $shop->showBargainGood($shop_id, $goods_id);
        if (empty($bargain_info)) {
            return json(['code' => $this->t_code, 'msg' => '不存在该商品']);
        }
        $user = new UserData();
        return json($user->createBargainOrder($goods_id, $shop_id, $bargain_info, $user_id));
    }

    /**
     * 好友砍价
     * @param $id
     * @param $open_id
     * @return \think\response\Json
     */
    public function editBargainOrder($id, $open_id)
    {
        if (Common::checkTableFields('drh_user_goods_bargain', 'id', $id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '砍价商品不存在']);
        }
        $user = new UserData();
        $info = $user->getBargainGoods($id);

        $bargain_open_id = explode(',', $info['bargain_open_id']);
        if (!empty($bargain_open_id)) {
            if (in_array($open_id, $bargain_open_id)) {
                return json(['code' => $this->f_code, 'msg' => '请勿重复砍价']);
            }
        }
        $bargain_num = $info['bargain_num'];
        if ($bargain_num == 0) {
            return json(['code' => $this->f_code, 'msg' => '砍价次数已满']);
        }
        if (empty($bargain_open_id)) {
            $bargain_open_id = $open_id;
        } else {
            $bargain_open_id = implode(',', $bargain_open_id) . ',' . $open_id;
        }
        $bargain_num--;
        $bargain_total_num = $info['bargain_total_num'] + 1;
        $user = new UserData();
        return json($user->editBargainOrder($id, $bargain_num, $bargain_open_id, $bargain_total_num));
    }

    /**
     * 砍价列表
     * @param $user_id
     * @param int $page
     * @param $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showBargainOrder($user_id, $page = 1, $pre = 15, array $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_user_goods_bargain', 'user_id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '砍价商品不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->bargainSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $user = new UserData();
        $data = $user->showBargainOrder($user_id, $page, $pre, $sort);
        $data = $this->getImage($data);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data,
                'total' => $user->total("bargain_num > 0 and user_id={$user_id}", 'drh_user_goods_bargain')
            ]
        ]);
    }

    /**
     * 展示砍价信息详情
     * @param $id
     * @return \think\response\Json
     */
    public function showBargainGoods($id)
    {
        if (Common::checkTableFields('drh_user_goods_bargain', 'id', $id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '砍价商品存在']);
        }
        $shop = new Shop();
        $shopData = new ShopData();
        $res = $shopData->getBargainGoodInfo($id);
        $id = $res['id'];
        $goods_info = json_decode($data = $shop->showGoods($res['goods_id'], 1, 1), true);
        if ($goods_info['code'] == $this->f_code) {
            return json($goods_info);
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'bargain_id' => $id,
                'goods' => $goods_info['data'],
            ]
        ]);
    }

    /**
     * 评价商品
     * @param $user_id
     * @param $order_num
     * @param $goods_id
     * @param $lv
     * @param string $msg
     * @return \think\response\Json
     */
    public function commentGoods($user_id, $order_num, $goods_id, $lv, $msg = '')
    {
        $res = Common::getTableValue('drh_goods_comment', 'id', ['user_id', 'order_num', 'goods_id'], [$user_id, $order_num, $goods_id]);
        if (!empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '请勿重复评价']);
        }
        $res = Common::getTableValue(
            'drh_goods_order',
            'goods_status',
            ['user_id', 'goods_id', 'order_num'],
            [$user_id, $goods_id, $order_num]
        );
        if ($res != 2) {
            return json(['code' => $this->f_code, 'msg' => '禁止评论']);
        }
        if (!in_array($lv, $this->lv)) {
            return json(['code' => $this->f_code, 'msg' => '评级错误']);
        }
        $user = new UserData();
        return json($user->commentGoods($user_id, $order_num, $goods_id, $lv, $msg));
    }

    /**
     * 用户中心显示
     * @param $open_id
     * @return \think\response\Json
     */
    public function showUserInfo($open_id)
    {
        $user = new UserData();
        $data = $user->showUserInfo(" user_open_id='{$open_id}'");
        $withdraw_money = $user->getWithdrawMoney($data['data']['id']);
        $data['data']['withdraw_money'] = $withdraw_money;
        $time = time();
        $time_start = strtotime(date("Y-m-d", $time));
        $data['data']['income_money'] = $user->getIncomeMoney($data['data']['id'], $time_start, $time);
        return json($data);
    }

    /**
     * 展示会员关系
     * @param $user_tel
     * @return \think\response\Json
     */
    public function showMemberRelationship($user_tel)
    {
        if (!Common::checkTel($user_tel)) {
            return json(['code' => $this->f_code, 'msg' => '手机号码格式不正确']);
        }
        $user = new UserData();
        $id = Common::getTableValue('drh_user_info', 'id', 'user_tel', $user_tel);
        if (empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '没有该用户']);
        }

        $p_res = $user->showMemberPR($id);
        $n_res = $user->showMemberNR($id);
        $p_res['next_one_id'] = $n_res['next_one_id'];
        $p_res['next_two_id'] = $n_res['next_two_id'];
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $p_res
        ]);
    }

    /**
     * 显示用户详情信息
     * @param $id
     * @return \think\response\Json
     */
    public function showAdminUserInfo($id)
    {
        if (Common::checkNumber($id)) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $user = new UserData();
        return json($user->showUserInfo(" id=$id"));
    }

    public function searchProxy($user_tel)
    {
        if (!Common::checkTel($user_tel)) {
            return ['code' => $this->f_code, 'msg' => '搜索格式错误'];
        }
        $user = new UserData();
        $res = $user->searchProxy($user_tel);
        $data = [];
        if (!empty($res)) {
            $data['status'] = $res['recover_status'];
            $data['type_lv'] = $res['type_lv'];
            $data['user_id'] = $res['id'];
            switch ($res['type_lv']) {
                case 1:
                    $data = $this->proxyInfo(1, $res['area_id'], $res['name']);
                    break;
                case 2:
                    $data = $this->proxyInfo(2, $res['area_id'], $res['name']);
                    break;
                case 0:
                    $data = [];
                    break;
                default:
                    throw new Exception('unknown mistake!', $this->f_code);
            }
        }
        return ['code' => $this->t_code, 'msg' => 'OK', 'data' => $data];
    }

    public function proxyInfo($type_lv, $area_id, $name)
    {
        if ($type_lv == 1) {
            $shop_where = " province_id={$area_id} ";
            $user_where = " province = '{$name}' ";
        } else {
            $shop_where = " city_id={$area_id} ";
            $user_where = " city = '{$name}' ";
        }

        $shop_total = Common::total($shop_where, 'drh_shop_city');
        $user_total = Common::total($user_where, 'drh_user_info');
        return ['shop_total' => $shop_total, 'user_total' => $user_total];
    }

    /**
     * 添加购物车
     * @param $user_id
     * @param $goods_id
     * @param $goods_attr_value
     * @param $goods_num
     * @return \think\response\Json
     */
    public function addShoppingCart($user_id, $goods_id, $goods_attr_value, $goods_num)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该用户']);
        }
        if (Common::checkTableFields('drh_goods', 'id', $goods_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商品']);
        }
        $res = Common::getTableValue('drh_goods', ['goods_stock', 'goods_attr_value'], 'id', $goods_id);
        $goods_attr = json_decode($res['goods_attr_value']);
        $goods_stock = $res['goods_stock'];
        if (!Common::checkNumber($goods_num)) {
            return json(['code' => $this->f_code, 'msg' => '商品数量必须为正整数']);
        }
        if ($goods_num > $goods_stock) {//是否超过最大库存
            return json(['code' => $this->f_code, 'msg' => '超过最大库存']);
        }
        if (!in_array($goods_attr_value, $goods_attr)) {//是否存在该商品属性
            return json(['code' => $this->f_code, 'msg' => '不存在该商品属性']);
        }
        $id = Common::getTableValue('drh_user_shopping_cart', 'user_id',
            ['user_id', 'goods_id', 'goods_attr_value'], [$user_id, $goods_id, $goods_attr_value]);
        if (!empty($id)) {
            return json(['code' => $this->t_code, 'msg' => '添加成功']);
        } else {
            $user = new UserData();
            $count = Common::total(" user_id={$user_id} ", "drh_user_shopping_cart");
            if ($count > 100) {
                return json(['code' => $this->t_code, 'msg' => '购物车最多100件商品,请删除后在从新添加']);
            }
            $time = time();
            return json($user->addShoppingCart($user_id, $goods_id, $time, $goods_attr_value, $goods_num));
        }
    }

    /**
     * 展示购物车
     * @param $user_id
     * @param $page
     * @param $pre
     * @return \think\response\Json
     */
    public function showShoppingCart($user_id, $page = 1, $pre = 15)
    {
        $res = Common::checkPageAndPre($page, $pre);
        if ($res['code'] != config('t_code')) {
            return json($res);
        }
        $user = new UserData();
        $data = $user->showShoppingCart($user_id, $page, $pre);
        $data = $this->getImage($data);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data,
                'total' => Common::total(" user_id={$user_id} ", "drh_user_shopping_cart")
            ]
        ]);
    }

    private function getImage($data)
    {
        foreach ($data as $k => $v) {
            $goods_img = json_decode($v['goods_img']);
            $goods_img = empty($goods_img[0]) ? '' : $goods_img[0];
            $data[$k]['goods_img'] = $goods_img;
//            $data[$k]['goods_attr_value'] = json_decode($v['goods_attr_value'], true);
        }
        return $data;
    }

    /**
     * 删除购物车
     * @param $user_id
     * @param $id
     * @param $goods_id
     * @return \think\response\Json
     */
    public function delShoppingCart($id, $user_id, $goods_id)
    {
        if (!Common::checkNumber($user_id) || !Common::checkNumber($goods_id) || !Common::checkNumber($id)) {
            return json(['code' => $this->t_code, 'msg' => '非法操作']);
        }
        $user = new UserData();
        return json($user->delShoppingCart($id, $user_id, $goods_id));
    }

    /**
     * 校验用户是否开店了
     * @param $user_id
     * @return \think\response\Json
     */
    public function checkUserShop($user_id)
    {
        if (!is_numeric($user_id)) {
            return json(['code' => $this->f_code, 'msg' => '非法用户']);
        }
        $user = new UserData();
        $res = $user->getUserShop($user_id);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        } else {
            return json(['code' => $this->t_code, 'msg' => 'OK', 'data' => $res['id']]);
        }
    }


    ///////////////////-------------------微信-----------------------////////////////////////

    public function getOpenId($code, $type = 1, $user_name = 1, $user_head_img = 1, $user_sex = 1, $encryptedData, $iv, $province = 1, $city = 1)
    {
        $iv=urldecode($iv);
        $encryptedData=urldecode($encryptedData);
//        $encryptedData="iME3ybH2wSv3P3I3IeqrmTIblTF0Wcq7kH8rRXtBpL5LwbblEAZ3efH8TYGjAKLjHq2vfgcJ4ON+v1dUzINbaabWhNpMdEtzXQ7Evs4aD7Dzt5SdL66mPT/TbiARNSLDH+osexoXjA79Imcy/gsnn5VOJ3B4lZUAm70fFQy3SouvaDuXwJEbL/ww+2mpQAacfMu/XwtHHiD1fr2wAv4uFacvTlvk26tMdD5y8wzxCj8VWajHiqdMRtkv6ipMRHCVZQFiRTssoHhx5CiyBFlACH+Hoo8ywMJJbEvs2+rmr1Q6X2b+SdmVMVi7k0zeC0IRUptt8pkSl4+37mMkatZTORMGnHrT05zOudPsvgOr70c9I0rm+l8HbDDhfXmAaDueW+qzyDOJbLrz4YcxEWY3xBkWBOLW4mJ2FQZH8m31JyTFCwwLhNHInngXc3PxfL6fwm7TjBMDCBkzjLUvDqnkzeB59qQ24tT3xaEdI54AOHSOpqPAPVzTqjUNQFZ+pVYJd2BIUv2vqSDrQDJNqLvWOg==";
//        $iv="5UvubdCYuOkwnxkFTZGhZQ==";
        if ($type == 1) {
//配置appid
            $app_id = config('app_id_v1');
//配置appscret
            $secret = config('secret_v1');
        } else {
//配置appid
            $app_id = config('app_id');
//配置appscret
            $secret = config('secret');
        }
//api接口
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$app_id}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
//获取GET请求
        //发送
        $str = file_get_contents($api);
        $str = json_decode($str, true);
        if (isset($str['unionid'])) {
            if (Common::checkTableFields('drh_user_info', 'union_id', $str['unionid']) == $this->t_code) {
                $str['status'] = 1;
            }
        } elseif (isset($str['openid'])) {
            if (Common::checkTableFields('drh_user_info', 'user_open_id', $str['openid']) == $this->t_code) {
                $str['status'] = 1;
            }
        }
        $sessionKey = $str['session_key'];
        $pc = new wxBizDataCrypt($app_id, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        $unionId = empty($str['unionid']) ? '' : $str['unionid'];
        $data = json_decode($data, true);
        if(empty($data['unionId']) && empty($str['unionid'])){
            return json(['code'=>$this->f_code,'msg'=>'网络连接错误,请稍后在试','data'=>['data'=>$data,
                'str'=>$str,'errorCode'=>$errCode,'iv'=>$iv,'encryptedData'=>$encryptedData]]);
        }
//        $errCode=0;
//        $data='{"openId":"oAtX64vSfDA4HjPEmY7nryQGRREc","nickName":"豪王","gender":1,"language":"zh_CN","city":"Chengdu","province":"Sichuan","country":"China","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEJdcgB4RFEH5enrD9pNBlpHSic3eicv49wM2kcr1ZUgMMDLctBV5DicNZPQIJzMFdIXCiak7OB5ib0R33w/132","unionId":"o2y8n54fxTEAGitPp3Sx_Ryk5XWE","watermark":{"timestamp":1550649170,"appid":"wx640ebd4c31a05f10"}}';
        if ($errCode == 0) {
            $unionId = empty($data['unionId']) ? $str['unionid'] : $data['unionId'];
            if (Common::checkTableFields('drh_user_info', 'user_open_id', $data['openId']) == $this->t_code) {
                Common::addTableFields('drh_user_info', 'user_open_id', $data['openId'], 'union_id', $unionId);
            }
        }
        if (empty($str['openid'])) {
            return json(['code' => $this->f_code, 'msg' => '系统繁忙请稍后再试']);
        }
        return $this->addUser($user_name, $user_head_img, $user_sex, $str['openid'], $unionId, $province, $city, $str['session_key']);
    }

    public function appletsCode()
    {
        $appid = config('app_id');
        $appsecret = config('secret');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        $res = Common::http_curl($url);
        $accessToken = $res['access_token'];
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
        $data = "{ \"path\": \"pages/index?query=1\", \"width\": 430 }";
        $res = $this->createAppletsCode($url, $data);
        file_put_contents('static/11.png', $res);
    }

    /**
     * 生成小程序二维码
     * @param $url
     * @param $data
     * @return mixed
     */
    public function createAppletsCode($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);//地址
        curl_setopt($ch, CURLOPT_POST, 1);//请求方式为post
        curl_setopt($ch, CURLOPT_HEADER, 0);//不打印header信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//返回结果转成字符串
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//post传输的数据。
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

    public function getVersionNumber()
    {
        Common::debug("测试消息", "测试内容", "test.txt");
    }
}